package anonymouschat.service;

import java.io.Serializable;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;

import anonymouschat.utils.Constants;
import anonymouschat.utils.Print;

/**
 * 
 * Contains String servername, string serverIP, int serverPort, PublicKey
 * publicKey
 * 
 */
public class ServerEntry implements Serializable {
	private static final long serialVersionUID = 4747248213859099964L;

	public ServerIdentObject serverIdent = null;

	/**
	 * Create a new server entry based on the server Identity
	 * @param serverIdent
	 */
	public ServerEntry(ServerIdentObject serverIdent) {
		Print.debug("Added ServerIdentity to ServerEntry");
		this.serverIdent = serverIdent;
	}

	/**
	 * 
	 * @param serverName
	 *            the name of the server
	 * @param serverIP
	 *            the server's IP
	 * @param serverPort
	 *            the server's port
	 * @param publicKey
	 *            the server's public key
	 */
	public ServerEntry(String serverName, String serverIP, int serverPort,
			PublicKey publicKey) {
		Print.debug("Created ServerEntry " + serverName + " at " + serverIP
				+ ":" + serverPort);
		this.serverIdent = null;
		this.serverName = serverName;
		this.serverIP = serverIP;
		this.serverPort = serverPort;
		this.publicKey = publicKey;
	}

	public String serverName;

	public int serverPort;

	public String serverIP;

	public PublicKey publicKey;

	private transient Cipher asymmetricCipherEngine = null;

	private SecretKey SymmetricKey = null;

	public void setPublicKey(PublicKey pub) {
		publicKey = pub;
	}

	public void setSymmetricKey(SecretKey sec) {
		SymmetricKey = sec;
	}

	public SecretKey getSymmetricKey() {
		return SymmetricKey;
	}
	
	/**
	 * Returns the Cipher object with this server's public key
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws NoSuchPaddingException
	 * @throws InvalidKeyException
	 */
	public Cipher getAsymmetricCipherEngine() throws NoSuchAlgorithmException,
			NoSuchPaddingException, InvalidKeyException {
		if (asymmetricCipherEngine == null) {
			Cipher enc = Cipher
					.getInstance(Constants.ASYMMETRIC_CYPHER_TYPE);
			enc.init(Cipher.ENCRYPT_MODE, publicKey);
			asymmetricCipherEngine = enc;
		}
		return asymmetricCipherEngine;
	}
}
